import { logout, getInfo, loginApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user: null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, payload) => {
    state.user = payload
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const resp = await loginApi(userInfo)
    if (resp.data) {
      // data里有数据则说明登陆成功
      // 存入全局状态里
      commit('SET_USER', resp.data)
    }
    return resp
  },

  // get user info
  async getInfo({ commit, state }) {
    let resp = await getInfo()
    if (typeof resp === 'string') {
      // 未登录，或者token已过期
      resp = JSON.parse(resp)
    } else {
      commit('SET_USER', resp.data)
    }
    return resp
  },

  // user logout
  logout({ commit, state }) {
    // 清除token、重置路由、清除状态
    localStorage.removeItem('adminToken')
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
